import urllib2
from BeautifulSoup import BeautifulSoup

COUNTRY_LIST = {}   # ip : countrycode

countryURL = "http://ipinfodb.com/ip_query_country.php?ip=%s"
cityURL = "http://ipinfodb.com/ip_query.php?ip=%s&timezone=false"

def getCountryFromIP(ip):
    # check first COUNTRY_LIST
    if COUNTRY_LIST.has_key(ip) == True:
        return COUNTRY_LIST[ip]

    # update from Web
    url = countryURL % ip
    page = urllib2.urlopen(url)
    soup = BeautifulSoup(page)
    # parse content
    for country in soup('countrycode'):
        new_country = country.contents[0]
        COUNTRY_LIST[ip] = new_country
        return new_country


getCountryFromIP("125.144.34.3")
